package com.share.hope.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.hope.entity.UserInfo;
import com.share.hope.entity.result.R;
import com.share.hope.mapper.UserInfoMapper;
import com.share.hope.service.UserInfoService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Override
    public R<String> register(UserInfo userInfo) {
        if (ObjectUtils.isEmpty(userInfo)) {
            return R.error("請檢查錄入的信息並重新提交..");
        }
        if (checkAccountNumber(userInfo.getAccountNumber())) {
            return R.error("該賬號已存在..");
        }
        UserInfo build = userInfo.toBuilder().password(userInfo.getPassword()).build();
        if (this.save(build)) {
            return R.ok("添加成功");
        }
        return R.error("添加失败");
    }

    private boolean checkAccountNumber(String accountNumber) {
        boolean boo = true;
        if (StringUtils.hasText(accountNumber)) {
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getAccountNumber, accountNumber);
            if (this.count(wrapper) == 0) {
                boo = false;
            }
        }
        return boo;
    }

    @Override
    public R<UserInfo> login(UserInfo userInfo) {
        UserInfo user = new UserInfo();
        if (checkAccountNumber(userInfo.getAccountNumber())) {
            UserInfo info = getInfoByAccountNumber(userInfo.getAccountNumber());
            if (!ObjectUtils.isEmpty(info) && userInfo.getPassword().equals(info.getPassword())) {
                user = info;
                return R.success(user);
            }
        }
        return R.loginErr(user);
    }

    private UserInfo getInfoByAccountNumber(String accountNumber) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("account_number", accountNumber);
        return this.getOne(wrapper);
    }

    @Override
    public R<String> updatePassword(UserInfo userInfo) {
        if (checkAccountNumber(userInfo.getAccountNumber())) {
            UserInfo info = getInfoByAccountNumber(userInfo.getAccountNumber());
            if (!ObjectUtils.isEmpty(info)) {
                if (userInfo.getPassword().equals(info.getPassword())) {
                    userInfo.setPassword(userInfo.getNewPassword());
                    this.updateById(userInfo);
                    return R.ok("設置新密碼成功..");
                }
            }
        }
        return R.error("賬號不存在或密碼錯誤..");
    }


}
